﻿using Newtonsoft.Json;
using PoundConsole.common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PoundConsole
{

    public class StableWeightDetector
    {
        private readonly int _requiredStableCount; // 需要的连续稳定次数
        private double? _lastValue;                // 上一次的值
        private int _currentStableCount;          // 当前连续稳定次数
        private bool _hasStableResult;            // 是否已获取稳定结果
        //private readonly  Queue<double> _readings = new Queue<double>(); // 数据队列
        public StableWeightDetector(Queue<double> _readings,int requiredStableCount = 3)
        {
            if (requiredStableCount < 3)
                throw new ArgumentException("稳定次数至少为3", nameof(requiredStableCount));

            _requiredStableCount = requiredStableCount;
            //Reset(_readings);
        }

        /// <summary>
        /// 添加新的称重数据
        /// </summary>
        /// <param name="weight">当前称重值</param>
        /// <returns>如果达到稳定条件则返回稳定值，否则返回null</returns>
        public double? AddReading(double weight)
        {
            // 如果已获取稳定结果，直接返回null
            if (_hasStableResult) return null;

            // 首次读取或值发生变化时重置计数器
            if (!_lastValue.HasValue || Math.Abs(weight - _lastValue.Value) > double.Epsilon)
            {
                _lastValue = weight;
                _currentStableCount = 1;
                return null;
            }

            // 值相同，增加稳定计数
            _currentStableCount++;
            // 达到稳定条件
            if (_currentStableCount >= _requiredStableCount)
            {
                _hasStableResult = true;
                return weight;
            }

            return null;
        }

        /// <summary>
        /// 重置检测器状态（用于新车辆检测）
        /// </summary>
        public void Reset(Queue<double> _readings)
        {
            _lastValue = null;
            _currentStableCount = 0;
            _hasStableResult = false;
            _readings.Clear();
        }

        public  async void OutputResult(double weightBound, Queue<double> _readings,string PortName) {
            // 创建检测器（要求连续4次相同）
            var detector = new StableWeightDetector(_readings,requiredStableCount: 4);

            // 模拟地磅数据（车辆停止后连续多次相同值）
            // double[] weightData = { 1500.0, 1520.0, 1520.0, 1520.0, 1520.0, 1520.0 };
            _readings.Enqueue(weightBound);
            //限制Queue长度
            if (_readings.Count>30)
            {
                _readings.Dequeue();
            }
            foreach (var weight in _readings)
            {
                double? stableWeight = detector.AddReading(weight);

                if (stableWeight.HasValue)
                {
                    if (stableWeight > 0) { 
                    Console.WriteLine($"{DateTime.Now }检测到{PortName}稳定重量: {stableWeight.Value} 吨");
                         LogHelper.WriteLog($"检测到{PortName}稳定重量: {stableWeight.Value} 吨");
                        //Program.idCardNo1 = "421083198312054910";
                        if (Program.idCardNo1!="" || Program.idCardNo2 != "" || Program.idCardNo3 != "")
                        {
                            // 准备JSON数据
                            string HardwareFlag = "";
                            string idCardString = "";
                            if (PortName=="COM1")
                            {
                                HardwareFlag = "Weighbridge1";
                                idCardString = Program.idCardNo1;
                            }
                            if (PortName == "COM2")
                            {
                                HardwareFlag = "Weighbridge2";
                                idCardString = Program.idCardNo2;
                            }
                            if (PortName == "COM3")
                            {
                                HardwareFlag = "Weighbridge3";
                                idCardString = Program.idCardNo3;
                            }
                            var data = new
                            {
                                carNo = "",
                                flag = HardwareFlag,
                                idCard = idCardString,
                                userName="",
                                weight= stableWeight.Value
                            };
                            if (!string.IsNullOrEmpty( idCardString))
                            {
                                //// 序列化对象为JSON字符串
                                string json = JsonConvert.SerializeObject(data);
                                await BaseClient.Post("http://101.200.187.8:8082/socket/weigh", json);
                                Console.WriteLine($"{DateTime.Now}读取身份证：{idCardString}，检测到{PortName}稳定重量: {stableWeight.Value} 吨,提交到服务端...");
                            }

                        }
                    }
                    detector.Reset(_readings); // 重置检测器准备下一辆车
                    if (PortName=="COM1")
                    {
                        Program.idCardNo1 = "";
                    }
                    if (PortName == "COM2")
                    {
                        Program.idCardNo2 = "";
                    }
                    if (PortName == "COM3")
                    {
                        Program.idCardNo3 = "";
                    }
                    System.Threading.Thread.Sleep(1000*5);
                    break;
                }
                else
                {
                    //Console.WriteLine($"{DateTime.Now}当前重量: {weight} kg (尚未稳定)");
                }
            }
        }
    }
    
}